﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Snake.Core;
using Snake.Mapping;
using Snake.ORM.Reflection;
using Snake.SQL;
using Snake.SQL.SQLNode;

namespace Snake.SQLBuilder.SQLNode
{
    public class Insert<T> : DbOperate
    {
        private readonly T entity;

        public Insert(DbContext context,T entity)
            : this(context.GetEntityMap(context.EntityType), context.NextAlias())
        {
            this.entity = entity;
        }

        public Insert(EntityMap entityMap, BracketedName alias)
        {
            this.EntityMap = entityMap;
            this.Alias = alias;
        }

        /// <summary>
        /// SQL 语句的构造
        /// </summary>
        /// <param name="writer"></param>
        public override void Render(SQLWriter writer)
        {
            writer.Append(SQLStrings.Insert);
            writer.Append(SQLStrings.Into);
            writer.Append(EntityMap.Table);
            List<PropertyMap> maps = EntityMap.Properties.ToList();
            if(EntityMap.Key.Property.PropertyType==typeof(int))
            {
                maps = EntityMap.Properties.Where(t => t.Column.Value != EntityMap.Key.Column.Value).ToList();
            }
            
            var values=new List<dynamic>();

            writer.AppendLine("(");
            for (var i = 0; i < maps.Count(); i++)
            {
                if (i > 0)
                    writer.Append(",");

                writer.AppendLine(EntityMap.Table + maps[i].Column);
                //拿属性的get方法的委托
                var getHandler = DynamicMethodCompiler.CreatePropertyGetHandler <T>(maps[i].Property);
                values.Add(getHandler(entity));
            }
            writer.AppendLine(")");
            writer.AppendLine(SQLStrings.Values);
            writer.AppendLine("(");

            for (int i = 0; i < values.Count; i++)
            {
                if(i>0)
                    writer.Append(",");
                writer.AppendLine("'"+values[i]+"'");
            }
         
            writer.AppendLine(")");

            writer.AppendLine(SQLStrings.Declare);
            writer.Append("@newId");
            writer.Append(SQLStrings.Int);
            writer.AppendLine(SQLStrings.Set);
            writer.Append("@newId=");
            writer.Append(SQLStrings.SCOPE_IDENTITY);

            writer.AppendLine(SQLStrings.Select);
            writer.Append("@newId");

        }

        public override bool VisitPath(DbContext context, PropertyInfo[] path, out BracketedName alias, out PropertyMap map)
        {
            throw new NotImplementedException();
        }
    }
}
